package com.test.myplayer;

import androidx.annotation.NonNull;
import androidx.appcompat.app.AppCompatActivity;
import androidx.core.app.ActivityCompat;
import androidx.core.content.PermissionChecker;

import android.Manifest;
import android.annotation.SuppressLint;
import android.content.pm.PackageManager;
import android.os.Build;
import android.os.Bundle;
import android.os.Environment;
import android.util.Log;
import android.view.SurfaceView;
import android.view.View;
import android.view.WindowManager;
import android.widget.Button;
import android.widget.SeekBar;
import android.widget.TextView;
import android.widget.Toast;

import java.io.File;

public class MainActivity extends AppCompatActivity implements SeekBar.OnSeekBarChangeListener {

    private String[] premissions = {Manifest.permission.READ_EXTERNAL_STORAGE, Manifest.permission.WRITE_EXTERNAL_STORAGE};
    private int REQUEST_CODE_PERMISSION = 0;

    private MyPlayer player;
    private SurfaceView surfaceView;
    private Button prepare, start;
    private TextView time;
    private SeekBar mSeekBar;
    private int mDuration = 0;
    private boolean isTouch;//用户是否拖拽了进度条
    private boolean isSeek; // 是否seek

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        getWindow().setFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON,
                WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON);
        setContentView(R.layout.activity_main);

        surfaceView = findViewById(R.id.surface_view);
        prepare = findViewById(R.id.prepare);
        start = findViewById(R.id.start);
        time = findViewById(R.id.time);
        mSeekBar = findViewById(R.id.seekBar);
        mSeekBar.setOnSeekBarChangeListener(this);

        if(!checkPermissions(premissions)){
            if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
                ActivityCompat.requestPermissions(this, premissions, REQUEST_CODE_PERMISSION);
            }
        }
        init();

        prepare.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                player.prepare();
            }
        });

        start.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                player.start();
            }
        });

        // Example of a call to a native method
//        TextView tv = findViewById(R.id.sample_text);
//        tv.setText(stringFromJNI());
    }

    private void init() {
        player = new MyPlayer();
        player.setSurfaceView(surfaceView);
        player.setDataSource(new File(Environment.getExternalStorageDirectory() + "/demo.mp4").getAbsolutePath());
        player.setOnPrepareListener(new MyPlayer.OnPrepareListener() {
            @Override
            public void onPrepared() {
                // 得到视频总时长
                mDuration = player.getDuration();

                runOnUiThread(new Runnable() {
                    @Override
                    public void run() {
                        if(mDuration != 0){
                            time.setText("00:00/" + getMinutes(mDuration) + ":" + getSeconds(mDuration));
                            time.setVisibility(View.VISIBLE);
                            mSeekBar.setVisibility(View.VISIBLE);
                        }
                        Toast.makeText(MainActivity.this, "准备好了", Toast.LENGTH_LONG).show();
                    }
                });
            }
        });
        player.setOnErrorListener(new MyPlayer.OnErrorListener() {
            @Override
            public void onError(final int errorCode) {
                runOnUiThread(new Runnable() {
                    @Override
                    public void run() {
                        Toast.makeText(MainActivity.this, "出错了，错误码：" + errorCode,
                                Toast.LENGTH_LONG).show();
                    }
                });
            }
        });
        player.setOnProgressListener(new MyPlayer.OnProgressListener() {
            @Override
            public void onProgress(final int progress) {
                // progress 底层ffmpeg 获取到的 当前播放时间（秒）
                if(!isTouch){
                    runOnUiThread(new Runnable() {
                        @Override
                        public void run() {
                            if (mDuration != 0) {
                                if (isSeek) {
                                    isSeek = false;
                                    return;
                                }
                                time.setText(getMinutes(progress) + ":" + getSeconds(
                                        progress) + "/" + getMinutes(mDuration) + ":" + getSeconds(
                                        mDuration));
                                mSeekBar.setProgress(progress * 100 / mDuration);
                            }
                        }
                    });
                }
            }
        });
    }

    @Override
    public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions,
                                           @NonNull int[] grantResults) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);
        if (requestCode == REQUEST_CODE_PERMISSION) {
            if (verifyPermissions(grantResults)) {
                init();
            }
        }
    }

    private boolean verifyPermissions(int[] grantResults) {
        for (int grantResult : grantResults) {
            if (grantResult != PackageManager.PERMISSION_GRANTED) {
                return false;
            }
        }
        return true;
    }

    @SuppressLint("WrongConstant")
    private boolean checkPermissions(String[] permissions) {
        if (Build.VERSION.SDK_INT < Build.VERSION_CODES.M) {
            return true;
        }
        for (String permission : permissions) {
            if (PermissionChecker.checkSelfPermission(this, permission) != PackageManager.PERMISSION_GRANTED) {
                return false;
            }
        }
        return true;

    }

    @Override
    protected void onStop() {
        super.onStop();
        player.stop();
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        player.release();
    }

    @Override
    public void onProgressChanged(SeekBar seekBar, int progress, boolean fromUser) {
        if (fromUser) {
            time.setText(getMinutes(progress * mDuration / 100) + ":" + getSeconds(
                    progress * mDuration / 100) + "/" + getMinutes(mDuration) + ":" + getSeconds(
                    mDuration));
        }
    }

    @Override
    public void onStartTrackingTouch(SeekBar seekBar) {
        isTouch = true;
    }

    @Override
    public void onStopTrackingTouch(SeekBar seekBar) {
        isTouch = false;
        isSeek = false;
        int seekBarProgress = seekBar.getProgress();//seekbar 的进度
        int playProgress = seekBarProgress * mDuration / 100;//转成 播放时间
        player.seek(playProgress);
    }

    private String getMinutes(int duration) {
        int minutes = duration / 60;
        if (minutes <= 9) {
            return "0" + minutes;
        }
        return "" + minutes;
    }

    private String getSeconds(int duration) {
        int seconds = duration % 60;
        if (seconds <= 9) {
            return "0" + seconds;
        }
        return "" + seconds;
    }

    /**
     * A native method that is implemented by the 'native-lib' native library,
     * which is packaged with this application.
     */
//    public native String stringFromJNI();
}
